package com.example.broadcast_offline;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;


import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {   //不可能每一个活动都要注册一个广播类  所以采用继承的方式
    private static final String TAG = "BaseActivity";
    private ForceOffLineReceiver receiver;    //一个广播声明   实现在下面
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityConllector.addActivity(this); //把继承的子类对象存起
        setTitle("软件1701 齐永超 20");
    }

    @Override
    protected void onResume() {  //程序启动时自动调用      oncreate start resume running  pause stop finish
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcast_offline.FORCE_OFFLINE");//把此活动的广播信息    定义  强制下线广播   结束Main
        receiver = new ForceOffLineReceiver();
        registerReceiver(receiver,intentFilter);    //注册广播  广播收听器和广播信息绑定
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null){
            unregisterReceiver(receiver);    //初始化广播   防止活动结束后广播仍在进行
            receiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityConllector.removeActivity(this);  //结束活动清除list
    }
    public class ForceOffLineReceiver extends BroadcastReceiver {
       @Override
        public void onReceive(final Context context, final Intent intent) {//已经注册过广播的活动发送广播后   在这里收听 context 指所继承此类 并发送intent的上下文对象
           Log.d(TAG, "onReceive: "+context.getApplicationContext());
            AlertDialog.Builder builder = new AlertDialog.Builder(context);//弹窗
            builder.setTitle("warning");
            builder.setMessage("您被强制下线, 请您重新登录!");
            builder.setCancelable(false); // 将对话框设置为不可取消
            // 给按钮添加注册监听
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 点击按钮所调用的方法
                    ActivityConllector.finishAll();//销毁所有的活动
                    Intent intent1 = new Intent(context, LoginActivity.class);
                    context.startActivity(intent1);
                }
            });
            builder.show();
        }
    }
}

